#include "messageeditarea.h"
#include <QFrame>
#include <QScrollBar>
#include <QScrollArea>
#include "historymessagewidget.h"
#include "soundrecorder.h"
#include "model/datacenter.h"
#include "toast.h"
#include "mainwidget.h"

using namespace model;

MessageEditArea::MessageEditArea(QWidget *parent): QWidget{parent}
{
    // 1. 设置尺寸
    this->setFixedHeight(200);
    this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

    // 2. 创建一个 QFrame 作为容器，用于显示边框
    QFrame* frame = new QFrame(this);
    frame->setFrameShape(QFrame::Box);
    frame->setFrameShadow(QFrame::Plain);
    frame->setLineWidth(1);
    frame->setStyleSheet("QFrame { border-top: 1px solid rgb(213, 213, 213); border-left: 1px solid rgb(213, 213, 213); }");

    // 3. 布局管理器
    QVBoxLayout* mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(0, 0, 0, 0);
    mainLayout->addWidget(frame);

    QVBoxLayout* layout = new QVBoxLayout(frame);
    layout->setSpacing(0);
    layout->setContentsMargins(5, 8, 5, 4);  // 修改上边距为8，确保不会覆盖上边框

    // 4. 按钮的布局管理器
    QHBoxLayout* hlayout = new QHBoxLayout();
    hlayout->setSpacing(5);
    hlayout->setContentsMargins(5, 8, 5, 4);
    hlayout->setAlignment(Qt::AlignLeft | Qt::AlignTop);
    layout->addLayout(hlayout);

    // 5. 设置按钮
    QString btnStyle =
        "QPushButton {"
        "   border: none;"
        "   background-color: transparent;"
        "   border-radius: 5px;"
        "}"
        "QPushButton:hover {"
        "   background-color: rgba(225, 225, 225, 128);"
        "}"
        "QPushButton:pressed {"
        "   background-color: rgba(213, 213, 213, 200);"
        "}";
    sendEmojiBtn = new QPushButton();
    sendEmojiBtn->setIcon(QIcon(":/resource/image/emoji.png"));
    sendEmojiBtn->setIconSize(QSize(24, 24));
    sendEmojiBtn->setFixedSize(36, 36);
    sendEmojiBtn->setStyleSheet(btnStyle);
    sendEmojiBtn->setToolTip("发送表情");
    hlayout->addWidget(sendEmojiBtn);

    sendImageBtn = new QPushButton();
    sendImageBtn->setIcon(QIcon(":/resource/image/image.png"));
    sendImageBtn->setIconSize(QSize(24, 24));
    sendImageBtn->setFixedSize(36, 36);
    sendImageBtn->setStyleSheet(btnStyle);
    sendImageBtn->setToolTip("发送图片");
    hlayout->addWidget(sendImageBtn);

    sendFileBtn = new QPushButton();
    sendFileBtn->setIcon(QIcon(":/resource/image/file.png"));
    sendFileBtn->setIconSize(QSize(24, 24));
    sendFileBtn->setFixedSize(36, 36);
    sendFileBtn->setStyleSheet(btnStyle);
    sendFileBtn->setToolTip("发送文件");
    hlayout->addWidget(sendFileBtn);

    sendSpeechBtn = new QPushButton();
    sendSpeechBtn->setIcon(QIcon(":/resource/image/sound.png"));
    sendSpeechBtn->setIconSize(QSize(24, 24));
    sendSpeechBtn->setFixedSize(36, 36);
    sendSpeechBtn->setStyleSheet(btnStyle);
    sendSpeechBtn->setToolTip("语音输入");
    hlayout->addWidget(sendSpeechBtn);

    showHistoryBtn = new QPushButton();
    showHistoryBtn->setIcon(QIcon(":/resource/image/history.png"));
    showHistoryBtn->setIconSize(QSize(24, 24));
    showHistoryBtn->setFixedSize(36, 36);
    showHistoryBtn->setStyleSheet(btnStyle);
    showHistoryBtn->setToolTip("查看聊天历史");
    hlayout->addWidget(showHistoryBtn);

    // 5. 添加多行编辑框
    textEdit = new QPlainTextEdit();
    textEdit->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    textEdit->setStyleSheet(R"(
        QPlainTextEdit {
            border: none;
            font: 400 14px 'Microsoft YaHei';
            color: #333;
            padding: 10px;
            background-color: transparent;
        }
    )");

    QScrollArea* temp = model::createScrollArea();
    textEdit->verticalScrollBar()->setStyleSheet(temp->verticalScrollBar()->styleSheet());
    textEdit->horizontalScrollBar()->setStyleSheet(temp->horizontalScrollBar()->styleSheet());
    delete temp;

    layout->addWidget(textEdit);

    // 6. 发送消息
    sendTextBtn = new QPushButton();
    sendTextBtn->setText("发送");
    sendTextBtn->setFixedSize(120, 40);
    sendTextBtn->setStyleSheet(R"(
        QPushButton{
            font-size: 14px;
            color: rgb(7, 193, 96);
            border: none;
            background-color: rgb(233, 233, 233);
            border-radius: 10px;
        }
        QPushButton:hover{
            background-color: rgb(225, 225, 225);
        }
    )");
    // sendTextBtn->setEnabled(false);
    layout->addWidget(sendTextBtn, 0, Qt::AlignRight | Qt::AlignVCenter);

    // 7. 关联信号槽
    initSignalSlot();
}

void MessageEditArea::initSignalSlot(){
     DataCenter* dataCenter = DataCenter::getInstance();
    // 1. 显示历史信息窗口
    connect(showHistoryBtn, &QPushButton::clicked, this, [=](){
        const QString& currentChatSessionId = dataCenter->getCurrentChatSessionId();
        if(currentChatSessionId.isEmpty()) return;
        HistoryMessageWidget* historyMessageWidget = new HistoryMessageWidget(this);
        historyMessageWidget->exec();
    });
    // 2. 发送文本消息
    connect(sendTextBtn, &QPushButton::clicked, this, &MessageEditArea::sendTextMessage);
    connect(dataCenter, &DataCenter::sendMessageDone, this, &MessageEditArea::addSelfMessage);
    // 3.  收到消息
    connect(dataCenter, &DataCenter::receiveMessageDone, this, &MessageEditArea::addOtherMessage);
    // 4. 关联 "发送图片" 信号槽
    connect(sendImageBtn, &QPushButton::clicked, this, &MessageEditArea::clickSendImageBtn);
    // 5. 关联 "发送文件" 信号槽
    connect(sendFileBtn, &QPushButton::clicked, this, &MessageEditArea::clickSendFileBtn);
    // 6. 关联 "发送语音" 信号槽
    connect(sendSpeechBtn, &QPushButton::pressed, this, &MessageEditArea::soundRecordPressed);
    connect(sendSpeechBtn, &QPushButton::released, this, &MessageEditArea::soundRecordReleased);
    // SoundRecorder* soundRecorder = SoundRecorder::getInstance();
    // connect(soundRecorder, &SoundRecorder::soundRecordDone, this, &MessageEditArea::sendSpeech);

}

void MessageEditArea::sendTextMessage(){
    // 1. 判断是否有会话选中
    DataCenter* dataCenter = DataCenter::getInstance();
    if(dataCenter->getCurrentChatSessionId().isEmpty()){
        LOG() << "当前未选中任何会话, 不会发送消息";
        Toast::showMessage("当前未选中任何会话, 不会发送消息");
        return;
    }
    // 2. 获取到输入框的内容, 看输入框里是否有内容. 啥都没输入, 此时也不做任何操作
    const QString& content = textEdit->toPlainText().trimmed();
    if (content.isEmpty()) {
        LOG() << "输入框为空";
        return;
    }

    // 3. 清空输入框已有内容
    textEdit->setPlainText("");

    // 4. 通过网络发送数据给服务器
    dataCenter->sendTextMessageAsync(dataCenter->getCurrentChatSessionId(), content);
}

void MessageEditArea::addSelfMessage(model::MessageType messageType, const QByteArray &content, const QString &extraInfo)
{
    DataCenter* dataCenter = DataCenter::getInstance();
    const QString& currentChatSessionId = dataCenter->getCurrentChatSessionId();

    // 1. 构造消息对象
    Message message = Message::makeMessage(messageType, currentChatSessionId,
                                           *dataCenter->getMyself(), content, extraInfo);
    dataCenter->addMessage(message);

    // 2. 把消息展示到消息展示区
    MainWidget* mainWidget = MainWidget::getInstance();
    MessageShowArea* messageShowArea = mainWidget->getMessageShowArea();
    messageShowArea->addMessage(false, message);

    // 3. 控制消息展示区滚动条在最后
    messageShowArea->scrollToEnd();

    // 4. 发送信号通知会话列表, 更新最后一条消息
    emit dataCenter->updateLastMessage(currentChatSessionId);
}

void MessageEditArea::addOtherMessage(const model::Message &message){
    // 1. 通过主界面拿到消息展示区
    MainWidget* mainWidget = MainWidget::getInstance();
    MessageShowArea* messageShowArea = mainWidget->getMessageShowArea();
    // 2. 把收到的新消息添加到消息展示区
    messageShowArea->addMessage(true, message);
    // 3. 控制滚动条
    messageShowArea->scrollToEnd();
    // 4. 提示收到消息
    Toast::showMessage("收到新消息");
}

void MessageEditArea::clickSendImageBtn(){
    DataCenter* dataCenter = DataCenter::getInstance();
    // 1. 先判定是否有选中会话
    if(dataCenter->getCurrentChatSessionId().isEmpty()){
        Toast::showMessage("您尚未选择任何会话, 不能发送图片!");
        return;
    }
    // 2. 弹出对话框
    QString filter = "Image Files(*.png *.jpg *.jpeg)";
    QString imagePath = QFileDialog::getOpenFileName(this, "选择图片", QDir::homePath(), filter);
    if(imagePath.isEmpty()){
        LOG() << "用户取消选择图片";
        return;
    }

    // 3. 读取图片内容
    QByteArray imageContent = loadFileToByteArray(imagePath);
    // 4. 发送请求
    dataCenter->sendImageMessageAsync(dataCenter->getCurrentChatSessionId(), imageContent);
}

void MessageEditArea::clickSendFileBtn(){
    DataCenter* dataCenter = DataCenter::getInstance();
    // 1. 先判定是否有选中会话
    if(dataCenter->getCurrentChatSessionId().isEmpty()){
        Toast::showMessage("您尚未选择任何会话, 不能发送文件!");
        return;
    }
    // 2. 弹出对话框
    QString filter = "*";
    QString path = QFileDialog::getOpenFileName(this, "选择文件", QDir::homePath(), filter);
    if (path.isEmpty()) {
        // 如果用户弹框之后, 没有真正选择文件, 而是取消了. 返回值就是 ""
        LOG() << "用户取消选择文件";
        return;
    }

    // 3. 读取文件内容 -- 不考虑大文件读取情况(如果是大文件需编写专门的网络通信接口, 实现 分片传输)
    QByteArray content = loadFileToByteArray(path);
    // 4. 传输文件
    QFile fileInfo(path);
    const QString& filename = fileInfo.fileName();
    dataCenter->sendFileMessageAsync(dataCenter->getCurrentChatSessionId(), filename, content);
}

void MessageEditArea::soundRecordPressed(){
    // 1. 判断是否选择会话
    DataCenter* dataCenter = DataCenter::getInstance();
    if(dataCenter->getCurrentChatSessionId().isEmpty()){
        LOG() << "未选中任何会话, 不能发送语音消息";
        return;
    }
    // 2. 切换图标
    sendSpeechBtn->setIcon(QIcon(":/resource/image/sound_active.png"));
    // 3. 开始录音
    SoundRecorder* soundRecoder = SoundRecorder::getInstance();
    soundRecoder->startRecord();
}

void MessageEditArea::soundRecordReleased(){
    // 1. 判断是否选择会话
    DataCenter* dataCenter = DataCenter::getInstance();
    if(dataCenter->getCurrentChatSessionId().isEmpty()){
        LOG() << "未选中任何会话, 不能发送语音消息";
        return;
    }
    // 2. 切换图标
    sendSpeechBtn->setIcon(QIcon(":/resource/image/sound.png"));
    // 3. 停止录音
    SoundRecorder* soundRecoder = SoundRecorder::getInstance();
    soundRecoder->stopRecord();
}

void MessageEditArea::sendSpeech(const QString &path){

}


























